<?php
/**
 * Created by PhpStorm.
 * User: caihoudao
 * Date: 2017/11/16
 * Time: 11:23
 */
namespace app\controllers\marketing;;

use Yii;
use app\models\marketing\PushGroupLog;
use yii\data\Pagination;

class PushGroupLogController extends \app\base\Controller {
    /**
     * 推送日志列表
     */
    private $mailTypeInfo = [
        0 => '全部',
        1 => '购物车邮件',
        2 => '浏览记录邮件',
    ];
    private $pushStepInfo = [
        0 => '全部',
        1 => '大数据',
        2 => '网站',
        3 => '邮件系统',
    ];
    private $siteType = [
        0 => '全部',
        1 => '电子',
        2 => '服装',
    ];
    public function actionIndex()
    {
        $data = [];
        $siteInfo = [];
        $defaultPageSize = 50;
        Yii::$app->params['now_addr'] = "系统业务日志";

        $mothod = strtolower(Yii::$app->request->getMethod());
        // 获取表单数据
        $formData = Yii::$app->request->$mothod();
        $site = Yii::$app->request->$mothod('site');
        $formData['type'] = isset($formData['type']) ? $formData['type'] : 1;
        // 当前用户所有有权限的站点
        $siteInfo_tmp = Yii::$app->authority->getMarketEmailAccessSite();

        if (isset($siteInfo_tmp) && is_array($siteInfo_tmp)) {
            foreach ($siteInfo_tmp as $siteInfo_tmp_k => $siteInfo_tmp_v) {
                $siteInfo[$siteInfo_tmp_v['site_id']] = $siteInfo_tmp_v['name'];
            }
        }
        if (empty($siteInfo)) {
            exit('你好，你没有任何网站的相关权限');
        }

        $formData['mail_type_id'] = isset($formData['mail_type_id']) ? $formData['mail_type_id'] : 0;
        $formData['push_step_id'] = isset($formData['push_step_id']) ? $formData['push_step_id'] : 0;
        $formData['site_type_id'] = isset($formData['site_type_id']) ? $formData['site_type_id'] : 0;
        // 时间相关
        $formData['startTime'] = isset($formData['startTime']) ? $formData['startTime'] : yii::$app->systime->date(time(), 'Y-m-d');


        // 当前搜索哪个网站的推送信息
        $formData['site_id'] = isset($formData['site_id']) ? $formData['site_id'] : 0;

        if ($formData['site_id']) {
            $flag = Yii::$app->authority->judgeMarketEmailHaveSite($formData['site_id']);
            if (!$flag) {
                $this->sysMsg('警告', '你的账号没有权限!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
            }
        }

        // 当前用户所有有权限的站点结束
        $siteInfo[0] = '全部';
        ksort($siteInfo);
        $siteInfoFlag = [];
        foreach($siteInfo as $k => &$item){//组装前端菜单联动需要打标记的数据结构

            if(isset(Yii::$app->params['sites']['marketing_email']['web_type'][1]['sites'][$k])){
                $siteInfoFlag[$k]['site_type'] = 1;
                $siteInfoFlag[$k]['site_name'] = $item;
            }else {
                $siteInfoFlag[$k]['site_type'] = 2;
                $siteInfoFlag[$k]['site_name'] = $item;
            }
            if(0 == $k){
                $siteInfoFlag[$k]['site_type'] = 0;
                $siteInfoFlag[$k]['site_name'] = $item;
            }

        }
        $siteInfoTmpIn = array_filter($siteInfoFlag,//跟据站点类型过滤对应的站点，减少sql语句in的组合数量提升索引性能
            function ($info) use ($formData) {
                if ($formData['site_type_id'] == 0){
                    return $info;
                }
                if ($formData['site_type_id'] == $info['site_type'] ) {
                    return $info;
                }

        });
        unset($siteInfo);
        $formData['siteInfo'] = $siteInfoFlag;
//        var_dump($siteInfo);


        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        $formUrl = explode('?',$http_type.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"])[0];
        // 分页参数相关
        $page = Yii::$app->request->$mothod('page') ? Yii::$app->request->$mothod('page') : 1;
        $pageSize = Yii::$app->request->$mothod('pagesize') ? Yii::$app->request->$mothod('pagesize') : $defaultPageSize;
        $formData['page'] = $page;
        $formData['pageSize'] = $pageSize;

        $formData['mailTypeInfo'] = $this->mailTypeInfo;
        $formData['pushStepInfo'] = $this->pushStepInfo;
        $formData['siteTypeInfo'] = $this->siteType;
        // 获取数据

        //组合条件
        $where = ' 1 ';
        if ($formData['startTime']) {
            $where .= " AND receive_date= '{$formData['startTime']}' ";
        }
        if ($formData['site_id']) {
            $where .= " AND site_id={$formData['site_id']} ";
        } else {
            $where .= ' AND site_id IN ('. implode(',', array_keys($siteInfoTmpIn))   .')';
        }
        if ($formData['site_type_id']) {
            $where .= " AND site_type = {$formData['site_type_id']} ";
        }else {
            $where .= ' AND site_type IN (1,2)';
        }

        if ($formData['mail_type_id']) {
            $where .= " AND mail_type = {$formData['mail_type_id']} ";
        }
        if ($formData['push_step_id']) {
            $where .= " AND step = {$formData['push_step_id']} ";
        }
        //分页
        $totalCountSql = <<<MYSQL
SELECT count(1) as total
FROM `push_group_log`
WHERE   $where
MYSQL;
//        echo $totalCountSql;
        $totalCount = Yii::$app->db->createCommand($totalCountSql)->queryScalar();
        $pages = new Pagination(['totalCount' =>$totalCount, 'pageSize' => $pageSize, 'defaultPageSize' => $pageSize]);
        $pageCount = $pages->getPageCount(); //页数
        $pageOther = ['totalCount' => $totalCount, 'pageCount' => $pageCount];
        $sql = <<<EOT
SELECT *
FROM `push_group_log`
WHERE   $where
ORDER BY site_type ASC,site_id ASC,mail_type ASC,step ASC
LIMIT $pages->offset, $pages->limit
EOT;
//       echo $sql;

        //数据
        $data = Yii::$app->db->createCommand($sql)->queryAll();
        // 分页相关
        // 渲染模版
        return $this->render('//marketing//push-group-log/list',[
            'data' =>$data,
            'site' => $site,
            'pages' => $pages,
            'formData' => $formData,
            'formUrl' => $formUrl,
        ]);
    }
}